package com.heima.storage.action;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.storage.entity.Storage;
import com.heima.storage.entity.StorageFreeze;
import com.heima.storage.service.IStorageFreezeService;
import com.heima.storage.service.IStorageService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author WSJ
 * @Date 2022-03-08-15:55
 * @Version 1.0 （版本号）
 */
@Service
public class StorageActionImpl implements StorageAction {
    @Autowired
    private IStorageService storageService;

    @Autowired
    private IStorageFreezeService freezeService;

    @Override
    public void deduct(String code, Integer count) {
        //商品数减少
        LambdaUpdateWrapper<Storage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Storage::getCommodityCode,code);
        wrapper.setSql("count=count-"+count);
        storageService.update(wrapper);
        //冻结商品数
        StorageFreeze freeze = new StorageFreeze();
        freeze.setXid(RootContext.getXID());
        freeze.setCode(code);
        freeze.setFreezeCount(count);
        freezeService.save(freeze);
    }

    @Override
    public boolean confirm(BusinessActionContext context) {
        //成功提交，删除冻结数据
        freezeService.removeById(context.getXid());
        return true;
    }

    @Override
    public boolean cancel(BusinessActionContext context) {
        //失败回滚
        StorageFreeze freeze = freezeService.getById(context.getXid());
        if (freeze!=null) {
            LambdaUpdateWrapper<Storage> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Storage::getCommodityCode,freeze.getCode());
            wrapper.setSql("count=count+"+freeze.getFreezeCount());
            storageService.update(wrapper);
            //删除冻结数据
            freezeService.removeById(freeze.getXid());
        }
        return true;
    }
}
